package map;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;

import javax.vecmath.Vector2d;
import javax.vecmath.Vector2f;


public class Scale {

	private final double faktor = 0.008;
	
	private static int name;
	
	private HashMap<String, Train> trains;
	public static HashMap<Integer, Station> stations;
	
	public Scale(HashMap<String, Train> trains){
		this.trains=trains;
	}
	
	public static void setStations(HashMap<Integer, Station> stations){
		Scale.stations=stations;
	}
	
	public HashMap<Integer, Station> findStations(Integer mainStationID){
		name=mainStationID;
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
		
		for (Train t: trains.values()){
			HashMap<Integer, Integer> s = findTrainStations(mainStationID, t);
			for (Integer i: s.keySet())
				if (map.containsKey(i)){
					if (map.get(i) > s.get(i))
						map.put(i, s.get(i));
				} else
					map.put(i, s.get(i));
		}
		
		
		Station mainStation = stations.get(mainStationID);
		HashMap<Integer, Station> ret = new HashMap<Integer, Station>();
		for (Integer i: map.keySet()){
			Station st = stations.get(i);
			int zeit= map.get(i);
			
			Vector2d vec=new Vector2d(st.getX()-mainStation.getX(), st.getY()-mainStation.getY());
			vec.normalize();
			vec.scale(zeit*faktor);
			st.setX(mainStation.getX()+vec.x);
			st.setY(mainStation.getY()+vec.y);
			
			ret.put(st.getId(), st);
		}
		
		ret.put(mainStation.getId(), mainStation);
		return ret;
		
	}
	
	public void changeView(boolean normal, HashMap<Integer, Station> st){
		if (!normal)
			findStations(name);
		else{
			for (Station s:st.values())
				s.restore();
		}
	}
	
	public static HashMap<Integer, Station> reset(){
		for (Station s: stations.values())
			s.restore();
		return stations;
	}
	
	private HashMap<Integer, Integer> findTrainStations(Integer mainStationID, Train train){
		HashMap<Integer, Integer> stations=new HashMap<Integer, Integer>();
		
		Waypoint main = findMainWaypoint(train.stations, mainStationID);
		
		if (main == null) return new HashMap<Integer, Integer>();
			
		for (Waypoint w: train.stations)
			if ((w.station!=main.station) && (main.departure < w.arrival))
				stations.put(w.station, w.arrival-main.departure);
		
		return stations;
		
		
	}
	
	private Waypoint findMainWaypoint(LinkedList<Waypoint> waypoints, int main){
		for (Waypoint w: waypoints)
			if (w.station==main)
				return w;
			
		return null;
	}

}
